<?php

namespace app\api\model;


use app\api\library\IntCode;
use app\api\model\UserCoupon as UserCouponModel;
use think\Db;
use think\Model;
use \app\api\model\Coupon as CouponModel;

class UserCoupon extends Model
{





    // 表名
    protected $name = 'user_coupon';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'is_used_text',
        'begin_time_text',
        'expire_time_text'
    ];

    public function couponinfo()
    {
        return $this->belongsTo('app\admin\model\Coupon', 'coupon_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function getIsUsedList()
    {
        return ['1' => __('Is_used 1'), '2' => __('Is_used 2')];
    }


    public function getIsUsedTextAttr($value, $data)
    {
        $value = $value ?: ($data['is_used'] ?? '');
        $list = $this->getIsUsedList();
        return $list[$value] ?? '';
    }


    public function getBeginTimeTextAttr($value, $data)
    {
        $value = $value ?: ($data['begin_time'] ?? '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getExpireTimeTextAttr($value, $data)
    {
        $value = $value ?: ($data['expire_time'] ?? '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setBeginTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setExpireTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    public function user()
    {
        return $this->belongsTo('app\admin\model\User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    /**
     * 检查优惠券的归属用户和是否已使用
     *
     * @param [type] $user_coupon_id
     * @param [type] $user_id
     * @return Object
     */
    public function checkUserOrUse($user_coupon_id, $user_id)
    {
        $row = $this->where('id', $user_coupon_id)->where('user_id', $user_id)->find();

        if (!$row) {
            throw new \Exception('未领取该优惠券或不可用！');
        }
        if ($row['is_used'] == 2) {
            throw new \Exception('该优惠券已使用！');
        }
        return $row;
    }

    public function receive($coupon_id,$user_id)
    {
        $model = new CouponModel();
        try {
            $row = $model->getCoupon($coupon_id)
                ->checkCoupon()
                ->checkOpen();
            //->checkNumber()
            //->checkMyNumber($user_id);
            //->checkReceiveTime();

            list($begin_time, $expire_time) = $row->getUseTime();
            Db::startTrans();
            try {
                //检测没问题，可领取
                (new UserCoupon())->save([
                    'coupon_id'   => $coupon_id,
                    'user_id'     => $user_id,
                    'begin_time'  => $begin_time,
                    'expire_time' => $expire_time
                ]);
                $row->setInc('received_num');
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                throw new \Exception($e->getMessage());
            }
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }

    //我的优惠券列表
    public static function tableList($param)
    {
        $pageNum = 10;
        if (isset($param['num']) && !empty($param['num'])) {
            $pageNum = $param['num'];
        }
        return self::field('id,coupon_id,user_id,is_used,expire_time,begin_time,createtime')
            ->with(['couponinfo' => function ($query) {
                $query->field('name,result,result_data,allow_num,begintime,endtime,mode,use_times');
            }])->where(function ($query) use ($param) {

                $time = time();
                if (isset($param['is_used']) && !empty($param['is_used'])) {
                    $query->where('is_used', $param['is_used']);
                }

                if (isset($param['user_id']) && $param['user_id'] != '') {
                    $query->where('user_id', $param['user_id']);
                }
                if (isset($param['begin_time']) && !empty($param['begin_time'])) {
                    $query->where('begin_time', '>', $time);
                }
                if (isset($param['expire_time']) && !empty($param['expire_time'])) {
                    $query->where('expire_time', '<', $time);
                }
            })->order('createtime desc')->paginate($pageNum);
    }

    //我的可以使用的优惠券【过滤掉条件不符合的】
    public static function myGoodsCoupon($user_id, $hotel_id,$money)
    {
        //$sql[] = [];
        //$sql[] = ['exp',Db::raw("FIND_IN_SET('{$hotel_id}',hotel_id)")];
        $time = time();
        //我的所有未使用的优惠券
        $list = self::field('*')->where('user_id', $user_id)
            ->where('is_used', 1)
            ->where('begin_time', '<', $time)
            ->where('expire_time', '>', $time)
            ->select();
        $data = [];

        foreach ($list as $item) {
            if (!empty($item['couponinfo'])) {

                $coupon = $item['couponinfo'];
                //dump($coupon);die;
                $coupon['user_coupon_id'] = $item['id'];
                $coupon['expire_time'] = $item['expire_time'];
                $coupon['begintime'] = $item['begin_time'];
                $coupon['usetime'] = date('Y-m-d H:i',$item['begin_time']).' - '.date('Y-m-d H:i',$item['expire_time']);
                if ($money>=$item['couponinfo']['result_data']['money']){
                    $data[] = $coupon->toArray();
                }
            }
        }
        return $data;
    }

    //恢复优惠券
    public static function resetUserCoupon($user_coupon_id)
    {
        if ($user_coupon_id) {
            self::where('id', $user_coupon_id)->update(['is_used' => 1,'order_id'=>0,'use_time'=>0]);
        }
        return true;
    }

    public function Coupon()
    {
        return $this->hasOne('Coupon', 'id', 'coupon_id');
    }

    //优惠券到期改状态
    public function expireCoupon()
    {
        $list = UserCouponModel::where('expire_time','<',time())->select();

        foreach ($list as $k=>$v){
            $user_coupon = UserCouponModel::get($v['id']);
            $user_coupon->is_used=3;
            $user_coupon->save();
        }
        //$this->success('请求成功');
    }
}
